from sign_generator.models import *

from django.http import HttpResponse,  HttpResponseRedirect 
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.conf import settings
from django.core.servers.basehttp import FileWrapper

from b9c.sign_generator import stl_sign_generator

import os, tempfile

def new(request):
    """
    Create a new sign
    """
    if request.method == 'POST':
        form = SignForm(request.POST)
        if form.is_valid():
            # Create a new Sign object.
            new_sign = form.save()
            # Create the related png file
            stl_sign_generator.generatePNGFile(new_sign.get_png(), new_sign.sign_text, new_sign.font)
            return HttpResponseRedirect(new_sign.get_absolute_url())
    else:
        form = SignForm()
 
    variables = RequestContext(request, {
        'form': form
    })
    return render_to_response('forms/new.html', variables, context_instance=RequestContext(request))


def returnZipFile(request, slug):
    sign = Sign.objects.filter(slug=slug)[0]

    os.chdir(settings.ZIP_DIR)
    zip_file = str(sign.slug + ".zip")
    dxf_file = str(sign.slug + ".dxf")
    scad_file = str(sign.slug + ".scad")

    # Get size and DXF
    ps_x, ps_y = stl_sign_generator.generateDXFFile(dxf_file, sign.sign_text, sign.font)
    # Make SCAD file
    print float(sign.x)
    print sign.x
    print type(sign.x)

    stl_sign_generator.generateScadFile(float(sign.x), float(sign.y), float(sign.z), float(sign.boarder), ps_x, ps_y, dxf_file, scad_file)
    # Make ZIP file
    stl_sign_generator.generateZIPFile(zip_file, dxf_file, scad_file)

    zip_data = open(zip_file, "rb").read()
    response = HttpResponse(zip_data, content_type='application/zip')
    filename = 'attachment; filename=' + str(sign.slug) + '.zip'
    response['Content-Disposition'] = filename
    return response


